﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using System.Web.Security;
using PNProject.EF;
using PNProject.Models;

namespace PNProject.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var member = Membership.GetUser();
            if (member != null)
            {
                var userName = member.UserName;
                Utils.TrackingUser(null, userName, "HomeController", "Index", Request.Url.PathAndQuery.ToString());
            }
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            var f = PNLibraries.RepaceAuthenLink("<p>h nghiệp tư nh&acirc;n.</p>[p]<a href=\"http://tuoitr.vn\">kjgkgj</a>xxx<a href=\"http://tuoitre.vn\">kjgkgj</a></p>[p]<a href=\"http://tuoitrccc.vn\">kjgkgj</a><img alt=\"\" src=\"/Uploads/images/Chitietca.png\" style=\"width: 459px; height: 25px;\" /></p>", "Đăng nhập","DNHinh");
            var iplocation = GetVisitorIpAddress();
            var ipVisit = new LocationIp();
            ipVisit.Id = Guid.NewGuid();
            ipVisit.CreatedDate = DateTime.Now;
            var ipExisted = StaticData.locationIpsRepo.GetOne(a => a.IP == iplocation);
            if (ipExisted == null)
            {
                ipVisit.IP = iplocation;
                ipVisit.Count = 1;
                StaticData.locationIpsRepo.Save(null, ipVisit);
            }
            else
            {
                ipVisit.Id = ipExisted.Id;
                ipVisit.IP = ipExisted.IP;
                ipVisit.Count = ipExisted.Count + 1;
                StaticData.locationIpsRepo.Save(ipExisted,ipVisit);
            }
            return View();
        }
        public string GetPublicIP()
        {
            String direction = "";
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                direction = stream.ReadToEnd();
            }

            //Search for the ip in the html
            int first = direction.IndexOf("Address: ") + 9;
            int last = direction.LastIndexOf("</body>");
            direction = direction.Substring(first, last - first);

            return direction;
        }
        private string GetUserIP()
        {
            string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipList))
            {
                return ipList.Split(',')[0];
            }

            return Request.ServerVariables["REMOTE_ADDR"];
        } 
        
        public string GetVisitorIpAddress()
        {
            string stringIpAddress;
            stringIpAddress = Request.Params["HTTP_X_FORWARDED_FOR"];
            if (stringIpAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
            {
                stringIpAddress = Request.Params["REMOTE_ADDR"];//we can use REMOTE_ADDR
            }
            return stringIpAddress;
        }
     

        public ActionResult About()
        {
            return View();
        }

        public ActionResult LeftBottom()
        {
            var currentCulture = CultureInfo.CurrentUICulture;
            bool lang = currentCulture.Name == "vi-VN"? true:false;
            string langtext = lang ? "" : "en-US/";
            ViewData["lang"] = langtext;
            var links = StaticData.linkRepo.GetSome(a => a.Lang == lang).ToList();
            if (links != null)
                ViewData["links"] = links;
            else
                ViewData["links"] = new List<Link>();

            VisitModel visit = new VisitModel();
            var vs = StaticData.settingRepo.GetOne(a => a.SKey == "visit");
            if (vs != null)
            {
                var arr = vs.SValue.Split('*');
                visit.Today = PNLibraries.PNVietNamNumberFormat(long.Parse(arr[0]), ",");
                visit.Month = PNLibraries.PNVietNamNumberFormat(long.Parse(arr[1]), ",");
                visit.Total = PNLibraries.PNVietNamNumberFormat(long.Parse(arr[2]), ",");
            }

            ViewData["visit"] = visit;
            
            return View();
        }

        public ActionResult RightBottom()
        {
            bool lang = CultureInfo.CurrentUICulture.Name == "vi-VN" ? true : false;
            ViewData["lang"] = lang;
            ViewData["news"] = StaticData.newsRepo.GetSome(a => a.Lang == lang && a.CType == 0, 4, 0).ToList();
            ViewData["questions"] = StaticData.feedbackRepo.GetSome(a => a.Lang == lang && a.Type == 1, 9, 0).ToList();
            ViewData["supports"] = StaticData.supportRepo.GetAll().ToList();            
            return View();
        }

        public ActionResult Banner()
        {
            bool lang = CultureInfo.CurrentUICulture.Name == "vi-VN" ? true : false;
            ViewData["banners"] = StaticData.bannerRepo.GetSome(a => a.Lang == lang).ToList();
            return View();
        }

        public ActionResult Slider()
        {
            bool lang = CultureInfo.CurrentUICulture.Name == "vi-VN" ? true : false;
            var list = StaticData.proRepo.GetSome(a => a.Lang == lang).OrderByDescending(a => a.LastUpdate).Take(8).ToList();
            ViewData["lang"] = lang;
            return View(list);
        }
    }
}
